import pygame
import numpy as np
import random
import sys
from pygame.locals import *

# 确保中文显示正常
pygame.init()
pygame.font.init()

class FindDifferencesGame:
    def __init__(self):
        # 设置游戏窗口
        self.WIDTH, self.HEIGHT = 1200, 800
        self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
        pygame.display.set_caption("找不同游戏")
        
        # 设置颜色
        self.WHITE = (255, 255, 255)
        self.BLACK = (0, 0, 0)
        self.RED = (255, 0, 0)
        self.GREEN = (0, 255, 0)
        self.BLUE = (0, 0, 255)
        self.YELLOW = (255, 255, 0)
        
        # 加载字体
        try:
            self.font = pygame.font.SysFont(["SimHei", "WenQuanYi Micro Hei", "Heiti TC"], 36)
            self.small_font = pygame.font.SysFont(["SimHei", "WenQuanYi Micro Hei", "Heiti TC"], 24)
        except:
            self.font = pygame.font.Font(None, 36)
            self.small_font = pygame.font.Font(None, 24)
        
        # 游戏状态
        self.game_state = "menu"
        self.score = 0
        self.time_left = 60  # 60秒
        self.start_time = 0
        self.differences_found = 0
        self.total_differences = 5
        
        # 图像相关
        self.image_size = (500, 500)
        self.image1_rect = pygame.Rect(50, 150, self.image_size[0], self.image_size[1])
        self.image2_rect = pygame.Rect(650, 150, self.image_size[0], self.image_size[1])
        
        # 创建游戏图像和差异
        self.image1 = None
        self.image2 = None
        self.differences = []
        self.create_images_with_differences()
        
        # 游戏循环控制
        self.clock = pygame.time.Clock()
        self.FPS = 60
        
        # 按钮
        self.start_button = pygame.Rect(self.WIDTH//2 - 100, self.HEIGHT//2, 200, 60)
        self.quit_button = pygame.Rect(self.WIDTH//2 - 100, self.HEIGHT//2 + 80, 200, 60)
        self.restart_button = pygame.Rect(self.WIDTH//2 - 100, self.HEIGHT//2 + 40, 200, 60)
        
        # 差异标记
        self.marked_differences = []
    
    def create_images_with_differences(self):
        """创建两个相似但有差异的图像"""
        # 创建基础图像
        self.image1 = pygame.Surface(self.image_size)
        self.image1.fill(self.WHITE)
        
        # 绘制背景元素
        self.draw_random_scene(self.image1)
        
        # 复制图像作为第二张
        self.image2 = self.image1.copy()
        
        # 清除之前的差异
        self.differences = []
        self.marked_differences = []
        self.differences_found = 0
        
        # 在第二张图像中创建差异
        for _ in range(self.total_differences):
            diff_pos = self.create_difference()
            self.differences.append(diff_pos)
    
    def draw_random_scene(self, surface):
        """绘制随机场景"""
        # 绘制一些随机的元素
        # 天空
        sky_rect = pygame.Rect(0, 0, self.image_size[0], self.image_size[1] * 2 // 3)
        pygame.draw.rect(surface, (135, 206, 235), sky_rect)
        
        # 地面
        ground_rect = pygame.Rect(0, self.image_size[1] * 2 // 3, self.image_size[0], self.image_size[1] // 3)
        pygame.draw.rect(surface, (34, 139, 34), ground_rect)
        
        # 太阳
        pygame.draw.circle(surface, (255, 215, 0), (400, 100), 50)
        
        # 云朵
        for _ in range(5):
            x = random.randint(50, self.image_size[0] - 100)
            y = random.randint(30, 150)
            size = random.randint(40, 80)
            pygame.draw.circle(surface, self.WHITE, (x, y), size)
            pygame.draw.circle(surface, self.WHITE, (x + size//2, y), size)
            pygame.draw.circle(surface, self.WHITE, (x - size//2, y), size)
        
        # 树木
        for _ in range(8):
            x = random.randint(30, self.image_size[0] - 30)
            y = self.image_size[1] * 2 // 3
            trunk_height = random.randint(50, 80)
            pygame.draw.rect(surface, (139, 69, 19), (x - 10, y - trunk_height, 20, trunk_height))
            # 树冠
            pygame.draw.circle(surface, (0, 100, 0), (x, y - trunk_height - 30), 40)
        
        # 花朵
        for _ in range(15):
            x = random.randint(20, self.image_size[0] - 20)
            y = random.randint(self.image_size[1] * 2 // 3, self.image_size[1] - 20)
            color = (random.randint(200, 255), random.randint(0, 50), random.randint(0, 50))
            pygame.draw.circle(surface, color, (x, y), 8)
            pygame.draw.circle(surface, (255, 255, 0), (x, y), 3)
        
        # 房子
        if random.random() > 0.3:
            x = random.randint(100, self.image_size[0] - 150)
            y = self.image_size[1] * 2 // 3 - 100
            # 房子主体
            pygame.draw.rect(surface, (255, 165, 0), (x, y, 100, 100))
            # 屋顶
            pygame.draw.polygon(surface, (139, 0, 0), [(x - 20, y), (x + 50, y - 50), (x + 120, y)])
            # 门
            pygame.draw.rect(surface, (139, 69, 19), (x + 40, y + 60, 20, 40))
            # 窗户
            pygame.draw.rect(surface, (173, 216, 230), (x + 20, y + 30, 20, 20))
            pygame.draw.rect(surface, (173, 216, 230), (x + 60, y + 30, 20, 20))
    
    def create_difference(self):
        """在第二张图像中创建差异"""
        # 尝试10次找到有效的差异位置
        for _ in range(10):
            x = random.randint(30, self.image_size[0] - 30)
            y = random.randint(30, self.image_size[1] - 30)
            
            # 确保差异不会重叠
            overlap = False
            for (dx, dy, _, _) in self.differences:
                if abs(dx - x) < 40 and abs(dy - y) < 40:
                    overlap = True
                    break
            
            if not overlap:
                # 随机选择差异类型
                diff_type = random.randint(1, 3)
                
                if diff_type == 1:
                    # 添加元素
                    color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
                    pygame.draw.circle(self.image2, color, (x, y), random.randint(10, 20))
                elif diff_type == 2:
                    # 删除元素（用背景色覆盖）
                    # 判断位置是天空还是地面
                    if y < self.image_size[1] * 2 // 3:
                        color = (135, 206, 235)  # 天空色
                    else:
                        color = (34, 139, 34)  # 地面色
                    pygame.draw.rect(self.image2, color, (x - 15, y - 15, 30, 30))
                else:
                    # 修改元素颜色
                    pygame.draw.rect(self.image2, self.RED, (x - 10, y - 10, 20, 20))
                
                return (x, y, 20, 20)  # 返回差异位置和大小
        
        # 如果找不到合适的位置，返回默认位置
        return (100, 100, 20, 20)
    
    def check_difference(self, pos):
        """检查用户点击是否找到差异"""
        # 转换点击位置到图像坐标系
        rel_x = pos[0] - self.image2_rect.x
        rel_y = pos[1] - self.image2_rect.y
        
        # 检查是否在第二个图像区域内
        if 0 <= rel_x < self.image_size[0] and 0 <= rel_y < self.image_size[1]:
            # 检查是否点击到差异
            for i, (dx, dy, dw, dh) in enumerate(self.differences):
                if i not in self.marked_differences:
                    if dx - dw <= rel_x <= dx + dw and dy - dh <= rel_y <= dy + dh:
                        # 找到差异
                        self.marked_differences.append(i)
                        self.differences_found += 1
                        self.score += 100
                        return True
        
        return False
    
    def draw_menu(self):
        """绘制游戏菜单"""
        self.screen.fill(self.BLUE)
        
        # 绘制标题
        title_text = self.font.render("找不同游戏", True, self.WHITE)
        title_rect = title_text.get_rect(center=(self.WIDTH//2, self.HEIGHT//2 - 100))
        self.screen.blit(title_text, title_rect)
        
        # 绘制开始按钮
        pygame.draw.rect(self.screen, self.GREEN, self.start_button)
        pygame.draw.rect(self.screen, self.BLACK, self.start_button, 3)
        start_text = self.font.render("开始游戏", True, self.BLACK)
        start_text_rect = start_text.get_rect(center=self.start_button.center)
        self.screen.blit(start_text, start_text_rect)
        
        # 绘制退出按钮
        pygame.draw.rect(self.screen, self.RED, self.quit_button)
        pygame.draw.rect(self.screen, self.BLACK, self.quit_button, 3)
        quit_text = self.font.render("退出游戏", True, self.BLACK)
        quit_text_rect = quit_text.get_rect(center=self.quit_button.center)
        self.screen.blit(quit_text, quit_text_rect)
        
        # 绘制游戏说明
        instructions = [
            "游戏说明:",
            "1. 在两张图片中找出所有不同之处",
            "2. 点击右侧图片中的差异位置",
            "3. 每找到一个差异获得100分",
            "4. 游戏时间为60秒"
        ]
        
        for i, line in enumerate(instructions):
            text = self.small_font.render(line, True, self.WHITE)
            text_rect = text.get_rect(center=(self.WIDTH//2, self.HEIGHT//2 + 180 + i * 30))
            self.screen.blit(text, text_rect)
    
    def draw_game(self):
        """绘制游戏界面"""
        self.screen.fill(self.WHITE)
        
        # 绘制两张图片
        self.screen.blit(self.image1, self.image1_rect)
        self.screen.blit(self.image2, self.image2_rect)
        
        # 绘制图片边框
        pygame.draw.rect(self.screen, self.BLACK, self.image1_rect, 3)
        pygame.draw.rect(self.screen, self.BLACK, self.image2_rect, 3)
        
        # 标记已找到的差异
        for i in self.marked_differences:
            dx, dy, dw, dh = self.differences[i]
            # 在第二个图像中标记
            pygame.draw.circle(self.screen, self.GREEN, 
                             (self.image2_rect.x + dx, self.image2_rect.y + dy), 
                             25, 3)
        
        # 绘制游戏信息
        score_text = self.font.render(f"分数: {self.score}", True, self.BLACK)
        self.screen.blit(score_text, (50, 50))
        
        time_text = self.font.render(f"时间: {self.time_left}秒", True, self.BLACK)
        self.screen.blit(time_text, (self.WIDTH//2 - 100, 50))
        
        diff_text = self.font.render(f"找到的差异: {self.differences_found}/{self.total_differences}", True, self.BLACK)
        self.screen.blit(diff_text, (self.WIDTH - 400, 50))
        
        # 绘制提示文字
        hint_text = self.small_font.render("点击右侧图片中的不同之处", True, self.BLACK)
        self.screen.blit(hint_text, (self.WIDTH//2 - hint_text.get_width()//2, 100))
    
    def draw_game_over(self):
        """绘制游戏结束界面"""
        # 半透明背景
        overlay = pygame.Surface((self.WIDTH, self.HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 180))
        self.screen.blit(overlay, (0, 0))
        
        # 绘制游戏结束文字
        if self.differences_found == self.total_differences:
            result_text = self.font.render("恭喜你！找到了所有差异！", True, self.GREEN)
        else:
            result_text = self.font.render("游戏结束！", True, self.RED)
        
        result_rect = result_text.get_rect(center=(self.WIDTH//2, self.HEIGHT//2 - 50))
        self.screen.blit(result_text, result_rect)
        
        # 绘制最终得分
        score_text = self.font.render(f"最终得分: {self.score}", True, self.YELLOW)
        score_rect = score_text.get_rect(center=(self.WIDTH//2, self.HEIGHT//2))
        self.screen.blit(score_text, score_rect)
        
        # 绘制重玩按钮
        pygame.draw.rect(self.screen, self.GREEN, self.restart_button)
        pygame.draw.rect(self.screen, self.BLACK, self.restart_button, 3)
        restart_text = self.font.render("再玩一次", True, self.BLACK)
        restart_text_rect = restart_text.get_rect(center=self.restart_button.center)
        self.screen.blit(restart_text, restart_text_rect)
        
        # 绘制退出按钮
        quit_rect = pygame.Rect(self.WIDTH//2 - 100, self.HEIGHT//2 + 120, 200, 60)
        pygame.draw.rect(self.screen, self.RED, quit_rect)
        pygame.draw.rect(self.screen, self.BLACK, quit_rect, 3)
        quit_text = self.font.render("退出游戏", True, self.BLACK)
        quit_text_rect = quit_text.get_rect(center=quit_rect.center)
        self.screen.blit(quit_text, quit_text_rect)
    
    def handle_events(self):
        """处理游戏事件"""
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            
            if event.type == MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                
                if self.game_state == "menu":
                    # 处理菜单点击
                    if self.start_button.collidepoint(pos):
                        self.start_game()
                    elif self.quit_button.collidepoint(pos):
                        pygame.quit()
                        sys.exit()
                
                elif self.game_state == "playing":
                    # 处理游戏中点击
                    found = self.check_difference(pos)
                    if found:
                        # 播放找到差异的音效（可选）
                        pass
                    
                    # 检查是否找到所有差异
                    if self.differences_found == self.total_differences:
                        self.game_state = "game_over"
                
                elif self.game_state == "game_over":
                    # 处理游戏结束界面点击
                    if self.restart_button.collidepoint(pos):
                        self.start_game()
                    elif pygame.Rect(self.WIDTH//2 - 100, self.HEIGHT//2 + 120, 200, 60).collidepoint(pos):
                        pygame.quit()
                        sys.exit()
    
    def start_game(self):
        """开始新游戏"""
        self.game_state = "playing"
        self.score = 0
        self.time_left = 60
        self.differences_found = 0
        self.start_time = pygame.time.get_ticks()
        self.create_images_with_differences()
    
    def update_time(self):
        """更新游戏时间"""
        if self.game_state == "playing":
            elapsed = (pygame.time.get_ticks() - self.start_time) // 1000
            self.time_left = max(0, 60 - elapsed)
            
            if self.time_left == 0:
                self.game_state = "game_over"
    
    def run(self):
        """游戏主循环"""
        while True:
            self.handle_events()
            self.update_time()
            
            # 绘制相应的界面
            if self.game_state == "menu":
                self.draw_menu()
            elif self.game_state == "playing":
                self.draw_game()
            elif self.game_state == "game_over":
                self.draw_game_over()
            
            pygame.display.flip()
            self.clock.tick(self.FPS)

# 主函数
if __name__ == "__main__":
    game = FindDifferencesGame()
    game.run()